const canvas = document.createElement('canvas');
const canvasCtx = canvas.getContext('2d');

canvas.width = 1920;
canvas.height = 1080;

function imageDataFromCanvas(canvasImageSource, width, height) {
  const scalingRatio = Math.min(
    1,
    canvas.width / width,
    canvas.height / height
  );
  const widthScaled = scalingRatio * width;
  const heightScaled = scalingRatio * height;

  canvasCtx.drawImage(canvasImageSource, 0, 0, widthScaled, heightScaled);
  console.log('3');
  return canvasCtx.getImageData(0, 0, widthScaled, heightScaled);
}

export function imageDataFromImage(imageElement) {
  const width = imageElement.naturalWidth;
  const height = imageElement.naturalHeight;
  console.log('2');
  return imageDataFromCanvas(imageElement, width, height);
}

export function imageDataFromVideo(videoElement) {
  const width = videoElement.videoWidth;
  const height = videoElement.videoHeight;

  return imageDataFromCanvas(videoElement, width, height);
}

export async function imageDataFromUrl(url) {
  if (url.startsWith('http') && url.includes(window.location.host) === false) {
    // eslint-disable-next-line no-alert
    alert('转换失败');
  }
  const image = document.createElement('img');
  image.src = url;

  const load = new Promise((resolve, reject) => {
    image.onload = () => {
      resolve();
    };
    image.onerror = () => {
      reject();
    };
  });

  await load;

  return imageDataFromImage(image);
}
